package spynx;

import java.io.File;
import java.io.IOException;

import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.Resource.Diagnostic;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;

import spynx.desl.DeslPackage;
import spynx.desl.DeslProgram;
import spynx.desl.proxies.ProxiesPackage;

public class ParseDesl {

	public static DeslProgram loadProgram(String input, ResourceSet rs) {
		DeslProgram prog = null;
		
		if (rs == null) rs = new ResourceSetImpl();
		Resource resource = rs.getResource(URI.createURI(input), true);
		EObject eobj = resource.getContents().get(0);
		EList<Diagnostic> errors = resource.getErrors();
		
		if (errors.size() > 0) {
			for(Diagnostic err: errors) 
				System.out.printf("Error: %s", err.getMessage());
		}
		else {
			prog = (DeslProgram) eobj;
			/*//List<InclusionDeclaration> inclusion = prog.getChildren(InclusionDeclaration.class);
			for (InclusionDeclaration incl: prog.getChildren(InclusionDeclaration.class))
				//rs.getResource(URI.createURI(incl.getImportURI()), true);
				loadProgram(incl.getImportURI(), rs);*/
		}
		
		return prog;
	}

	
	/**
	 * @param args
	 * @throws IOException 
	 */
	@SuppressWarnings("unused")
	public static void main(String[] args) throws IOException {
		DeslPackage einstance = DeslPackage.eINSTANCE; // register EistarPackage
		ProxiesPackage proxies = ProxiesPackage.eINSTANCE;
		new DeslStandaloneSetup().createInjectorAndDoEMFRegistration();

		// syntax: ParseDesl [options] <file.desl> arguments
		//String input = "../../runtime-EclipseApplication/Test/redhat.desl";
		String input = "chrome_nvd.desl";
		if (args.length > 0)
			input = args[0];
		File fi = new File(input);
		if (!fi.exists()) {
			if (!input.toLowerCase().endsWith(".desl"))
				fi = new File(input + ".desl");
			if (!fi.exists()) {
				System.out.println("Input file not found.");
				System.exit(1);
			}
		}
		//String input = "firefox_nvd.desl";
		ResourceSetImpl rs = new ResourceSetImpl();
		DeslProgram prg = loadProgram(input, rs);
		
		//prg.run(new CharSequenceStream("nvd/2011-06-07/nvdcve-2.0-2010.xml", 2048));
		prg.run(null);
	}

}
